import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//这个类里的属性务必是public 或者 是 带有 public的get set 方法
//务必要有无参版本的构造方法
class Student{
    public int studentId;
    public String studentName;
}
@WebServlet("/json")
public class JsonServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //此处假设请求的body格式为
        //{studentId:10,studentName:"张三"}
        //jackson 提供的核心类
        //一个方法叫readValue,把json格式的数据转成java 的对象
        //还有一个方法叫做writeValueAsString,把Java对象转成json格式的字符串
        ObjectMapper objectMapper=new ObjectMapper();
        //readValue第一个参数可以是字符串，也可以是输入流
        Student s=objectMapper.readValue(req.getInputStream(),Student.class);
        //第二个参数是一个类对象，类对象也就是要解析出来的对象的类
        //objectMapper.writeValueAsString();
        System.out.println(s.studentId);
        System.out.println(s.studentName);
        resp.setContentType("text/html; charset=utf8");
        resp.getWriter().write(s.studentId+","+s.studentName);
    }
}
